<template>
  <view>
    <view class="row" @click="open">
      <view class="row-content">
        <text v-if="!label && placeholder" class="row-placeholder">{{ placeholder }}</text>
        <text v-if="label">{{ label }}</text>
      </view>
      <uni-icons type="forward" size="18" color="#999"></uni-icons>
    </view>
    <uni-popup ref="popup" type="bottom" class="popup" @maskClick="onClose">
      <view class="popup-content">
        <view class="picker-header">
          <view @click="onClose">取消</view>
          <view v-if="title" class="packer-title">{{ title }}</view>
          <view @click="onConfirm">确定</view>
        </view>
        <picker-view :value="index" @change="onChange" class="picker">
          <picker-view-column>
            <view class="picker-row" v-for="item in options" :key="item[valueKey]">
              {{ item[labelKey] }}
            </view>
          </picker-view-column>
        </picker-view>
      </view>
    </uni-popup>
  </view>
</template>
<script>
export default {
  props: {
    placeholder: String,
    value: [String, Number],
    title: String,
    options: {
      type: Array,
      default: () => []
    },
    labelKey: {
      type: String,
      default: 'label'
    },
    valueKey: {
      type: String,
      default: 'value'
    }
  },
  data() {
    return {
      index: [0]
    }
  },
  methods: {
    // 打开
    open() {
      const idx = this.options.findIndex((item) => item[this.valueKey] == this.value)
      this.index = [idx > -1 ? idx : 0]
      this.$refs.popup.open()
    },
    onClose() {
      this.$refs.popup.close()
    },
    onConfirm() {
      let obj = this.options[this.index[0]]
      const oldVal = this.value
      const val = obj[this.valueKey]
      this.$emit('input', val)
      if (oldVal !== val) {
        this.$emit('change', obj)
      }
      this.$refs.popup.close()
    },
    onChange(e) {
      this.index = e.detail.value
    }
  },
  computed: {
    label() {
      const obj = this.options.find((item) => item[this.valueKey] == this.value)
      if (obj) {
        return obj[this.labelKey]
      }
      return ''
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .bottom {
  margin-bottom: 0 !important;
}

.row {
  height: 52px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  width: 100%;
  box-sizing: border-box;

  .row-content {
    flex: 1;
    text-align: right;
    word-wrap: break-word;
    display: inline-block;
    width: 200rpx;
    overflow: hidden;
  }

  .row-placeholder {
    color: #bbbbbb;
  }
}

.popup-content {
  background: #fff;
}

.picker-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 0 20rpx;
  padding: 20rpx 0;
}

.picker {
  height: 490rpx;
}

.picker-row {
  text-align: center;
  line-height: 70rpx;
  text-overflow: ellipsis;
}

.packer-title {
  font-size: 30rpx;
}
</style>
